package com.yunc.auth.controller;

import com.alibaba.fastjson.JSONObject;
import com.yunc.auth.config.utils.R;
import com.yunc.auth.constants.AuthConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LogoutController {

    private final RedisTemplate<String, Object> redisTemplate;

    @DeleteMapping("/oauth2/logout")
    public R logout() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String jwtPayload = request.getHeader(AuthConstants.JWT_PAYLOAD_KEY);
        JSONObject jsonObject = JSONObject.parseObject(jwtPayload);
        // JWT唯一标识
        String jti = jsonObject.getString("jti");
        // JWT过期时间戳
        long exp = jsonObject.getLong("exp");
        long currentTimeSeconds = System.currentTimeMillis() / 1000;
        // token已过期，无需加入黑名单
        if (exp < currentTimeSeconds) {
            return R.ok();
        }
        redisTemplate.opsForValue().set(AuthConstants.TOKEN_BLACKLIST_PREFIX + jti, null, (exp - currentTimeSeconds), TimeUnit.SECONDS);
        return R.ok();
    }

    
}
